import axios from 'axios'
import { LOCAL_STORAGE_KEYS } from '@/constant'
import API from '@/http'

export function setupPostbackParams() {
  const searchParams = new URL(window.location.href).searchParams

  const cid = searchParams.get('cid')
  if (cid) localStorage.setItem(LOCAL_STORAGE_KEYS.POSTBACK_CID, cid)

  const share_aff = searchParams.get('share_aff') || searchParams.get('ch') // 後端說有時候 share_aff 是給在 ch 裡面...
  if (share_aff) localStorage.setItem(LOCAL_STORAGE_KEYS.POSTBACK_SHARE_AFF, share_aff)

  if (cid && share_aff) {
    localStorage.setItem(LOCAL_STORAGE_KEYS.POSTBACK_PARAMS, JSON.stringify({ cid, share_aff }))
  }
}

/**
 * Postback share_aff & cid 給後端
 */
export async function postback() {
  const postbackParams = localStorage.getItem(LOCAL_STORAGE_KEYS.POSTBACK_PARAMS)
  if (postbackParams === null) {
    return
  }
  try {
    const { cid, share_aff } = JSON.parse(postbackParams)
    if (cid && share_aff) {
      const postbackUrl = await API.App.postback({ data: { share_aff, cid } })
      await axios.get(postbackUrl)
    }
  } catch (e) {
    console.error(e)
  } finally {
    localStorage.removeItem(LOCAL_STORAGE_KEYS.POSTBACK_PARAMS)
  }
}
